import http from '@/utils/request.js'

export default {
	state: {
		//userInfo: uni.getStorageSync('userInfo'),
		token: uni.getStorageSync('token'),
		userName: uni.getStorageSync('userName'),
		nickName: uni.getStorageSync('nickName'),
		avatar: uni.getStorageSync('avatar'),
		roles: uni.getStorageSync('roles'),
		permissions: uni.getStorageSync('permissions'),

		// 业务相关
		todayStat: uni.getStorageSync('todayStat'),
	},
	mutations: {
		SET_TOKEN(state, token) {
			state.token = token;
			uni.setStorageSync('token', token);
		},
		SET_userName(state, userName) {
			state.userName = userName;
			uni.setStorageSync('userName', userName);
		},
		SET_nickName(state, nickName) {
			state.nickName = nickName;
			uni.setStorageSync('nickName', nickName);
		},
		SET_avatar(state, avatar) {
			state.avatar = avatar;
			uni.setStorageSync('avatar', avatar);
		},
		SET_todayStat(state, todayStat) {
			state.todayStat = todayStat;
			uni.setStorageSync('todayStat', todayStat);
		},
		RESET_ALL(state) {
			//清理本地数据缓存。
			uni.clearStorage()
			state.token = ""
			state.userName = ""
			state.nickName = ""
			state.avatar = ""
			state.roles = []
			state.permissions = []
			state.todayStat = {
				order_count: 0,
				order_amount: 0,
				received_amount: 0
			}
		},
	},
	actions: {
		Login(store, loginForm) {
			return new Promise((resolve, reject) => {
				http.post("/sysUser/login", loginForm).then(res => {
					store.commit('SET_TOKEN', res.data.token)
					// store.dispatch("GetInfo")
					resolve()
				}).catch(error => {
					reject(error)
				})
			})
		},
		GetInfo(store) {
			return new Promise((resolve, reject) => {
				http.get("/sysUser/getInfo").then(res => {
					store.commit('SET_userName', res.data.user_name)
					store.commit('SET_nickName', res.data.nick_name)
					store.commit('SET_avatar', res.data.avatar)
					// store.dispatch('InitDict')
					resolve(res)
				}).catch(error => {
					uni.reLaunch({ // 跳转到登录页
						url: '/pages/login'
					})
				})
			})
		},
		async GetTodayStat(store) {
			const res = await http.get("/sale/today-stats")
			store.commit('SET_todayStat', res.data)
		},
		logOut(store) {
			//const logOutResult = await http.post("/user/logOut")
			// store.commit('RESET_ALL')
		}
	},
};